// components/game/game.js
// component.js

const beh = require('../behavior.js')

const spirits = [
  {
    key: 1,
    icon: "../../images/hanbao.png",
  },
  {
    key: 2,
    icon: "../../images/jiaozi.png",
  },
  {
    key: 3,
    icon: "../../images/kouxiangtang.png",
  },
  {
    key: 4,
    icon: "../../images/mantou.png",
  },
  {
    key: 5,
    icon: "../../images/paomian.png",
  },
  {
    key: 6,
    icon: "../../images/shutiao.png",
  },
  {
    key: 7,
    icon: "../../images/tiantianquan.png",
  },
  {
    key: 8,
    icon: "../../images/tiantong.png",
  },
  {
    key: 9,
    icon: "../../images/xiangcaobingqilin.png",
  },
  {
    key: 10,
    icon: "../../images/xuegao.png",
  }
  
];
const assistNum = 10;
const layerNum = 10;
const ruleNum = 3;
Component({
  /**
   * 组件的属性列表
   */
 
  behaviors: [beh],

  properties: {
    count: {
      type: Number,
      default: 33
    },
    vh:{
      type:String,
    },
    vw:{
      type:String
    }
  
  },

  /**
   * 组件的初始数据
   */
  data: {
    allItems: [],
    isOver: false,
    isVictory: false,
    rangeNum: 0,
    toupNum: 110,
    revokeNum: 0,
    history: [],
    testArr:[{id:1,name:'zs'},{id:2,name:'las'}]
   
  },
lifetimes:{
  
  attached:function(){

    this.renew()
    // console.log(this.data.hallItems);
    // console.log(this.properties);
    // console.log(this.renew);
    // console.log(this.properties.assistLeft);
    // console.log(this.properties.assistRight);
// console.log(this.properties.slotItems);

  }
},
observers:{

},
computed:{
  //右侧重置
  assistLeft() {
    let items = this.data.allItems
      .filter((x) => x.position == "assist-left" && !x.purge)
      .sort((a, b) => b.layer - a.layer);

    return items.map((item, idx) => {
      return {
        ...item,
        style: { left: idx * 7 + "px" },
      };
    });
  },
  // 左侧重置
  assistRight() {
    // console.log('assistRight');
    let items = this.data.allItems
      .filter((x) => x.position == "assist-right" && !x.purge)
      .sort((a, b) => b.layer - a.layer);

    return items.map((item, idx) => {
      return {
        ...item,
        style: { right: idx * 7 + "px" },
      };
    });
  },
  slotItems() {
    
    // console.log(' computed slotItems');
    let items =this.data.allItems
      .filter((x) => x.position == "slot")
      .sort((a, b) => a.order - b.order);
      // console.log(items);
    return items.map((item, idx) => {
      return {
        ...item,
        style: { left: idx * 40 + "px" },
      };
    });
  },
  hallItems() {
    
    let items = this.data.allItems.filter((x) => x.position == "hall");
    items = items.map((item) => {
      let deviation = item.layer % 2 == 1 ? 0 : 25;
      let cols = item.layer % 2 == 1 ? 7 : 6;
      // console.log('cols',cols);
      let sno = item.sno;
      // console.log('sno',sno);
      let left = (sno % cols)*50 + deviation;
      let top = Math.floor(sno / cols)*50 + deviation;
      item.coordinate = {
        left,
        top,
      };

      return {
        ...item,
        style: {
          top: top + "px",
          left: left + "px",
          zIndex: item.layer,
        },
      };
    });
    items.forEach((item) => {
      if (!items.find((x) => x.layer > item.layer)) {
        item.isTop = true;
        return;
      }
         if (
          !items.find(
            (x) =>
              x.id != item.id &&
              x.layer > item.layer &&
              //左上
              ((x.coordinate.top == item.coordinate.top - 25 &&
                x.coordinate.left == item.coordinate.left - 25) ||
                //右下
                (x.coordinate.top == item.coordinate.top + 25 &&
                  x.coordinate.left == item.coordinate.left + 25) ||
                //右上
                (x.coordinate.top == item.coordinate.top - 25 &&
                  x.coordinate.left == item.coordinate.left + 25) ||
                //左下
                (x.coordinate.top == item.coordinate.top + 25 &&
                  x.coordinate.left == item.coordinate.left - 25) ||
                (x.coordinate.top == item.coordinate.top &&
                  x.coordinate.left == item.coordinate.left))
          )
        ) {
          item.isTop = true;
          return;
        }
        item.isTop = false;
      });
      return items;
  },
  toupItems() {
    let items = this.data.allItems
      .filter((x) => x.position == "to-up")
      .sort((a, b) => {
        a.order - b.order;
      });
      // console.log(items);

    return items.map((item) => {
      return {
        ...item,
        style: {
          left: (item.order % 3) * 40 + 10+"px",
          zIndex: item.order,
        },
      };
    });
  },
},
  /**
   * 组件的方法列表
   */
  methods: {
     //新的开始
     renew() {
      //  console.log('renew被调用');
      //  console.log( this.properties.count);
      //  console.log(ruleNum);
      let items = [];
      for (let i = 0; i < this.properties.count; i++) {
        let spirit = Math.floor(Math.random() * spirits.length);
        for (let j = 0; j < ruleNum; j++) {
          items.push({
            id: i * ruleNum + j,
            spirit: spirits[spirit],
            order: Math.random(),
          });
        }
      }
      items = items.sort((a, b) => a.order - b.order);
      items = this.resetPosition(items, assistNum, assistNum, layerNum);
// console.log(items);
      // this.allItems = items;
      this.setData({
        allItems:items
      })
      // console.log(this.data.allItems);
      // this.data.isOver = false;
      this.setData({
        isOver:false
      })
    
      // this.isVictory = false;
      this.setData({
        isVictory:false,
        rangeNum:1,
        toupNum:112,
        revokeNum:1,
        history:[]
      })
      // this.rangeNum = 1;
      // this.toupNum = 2;
      // this.revokeNum = 1;
      // this.history = [];
    },
    //辅助点击
    assistClick(e) {
      let item = e.target.dataset.item
      // console.log(item);
      // console.log("this",this);
      // console.log(this.data);
      if (this.data.isOver) {
        return;
      }
      let items =
        item.position == "assist-left" ? this.properties.assistLeft : this.properties.assistRight;
      if (items.find((x) => x.layer < item.layer)) {
        return;
      }
      this.slotAddItem(item);
    },
    //辅助点击
    hallClick(e) {
      // console.log(e);
      // console.log(e.target.dataset);
      let item = e.target.dataset.item
      // console.log(item);
      // console.log(this);
      if (this.data.isOver) {
        console.log('isOver');
        return;
      }
      if (!item.isTop) {
        console.log('is not the Top');
        return;
      }
      this.slotAddItem(item);
    },
    toupClick(e) {
      let item = e.target.dataset.item
      if (this.isOver) {
        return;
      }
      this.slotAddItem(item);
    },
    //添加
    slotAddItem(item) {
      // console.log(this);
      let items = this.data.allItems
        .filter((x) => x.position == "slot")
        .sort((a, b) => a.order - b.order);
      item.order = items.length;
      let idx = 0;
      // console.log(items);
      items.forEach((s) => {
        let spirit = this.data.allItems.find((x) => x.id == s.id);
        spirit.order = idx++;
        if (item.spirit.key == spirit.spirit.key) {
          // console.log(idx);
          item.order = idx++;
        }
      });

      let his = [];
      his.push({
        id: item.id,
        position: item.position,
      });
      //找到打当前索引
      // let spirit = this.data.allItems.find((x) => x.id == item.id);
      // spirit.position = "slot";
      // spirit.order = item.order;
    //  console.log('this.setData.allItems');
     this.data.allItems.forEach((c)=>{
      if(c.id==item.id){
        // console.log(c);
        c.position='slot'
        c.order=item.order
        return
      }
    })
    //forEach无法触发computed属性
      this.setData({
        allItems: this.data.allItems
      })
      // console.log(this.data);
      items = this.data.allItems.filter(
        (x) => x.position == "slot" && x.spirit.key == item.spirit.key
      );
      // console.log(items);
      if (items.length == 3) {
        items.forEach((s) => {
          let spirit = this.data.allItems.find((x) => x.id == s.id);
          his.push({
            id: spirit.id,
            position: spirit.position,
          });
          spirit.position = "dispel";
        });
      }
      // this.data.history.push(his);
      let history = [his,...this.data.history]
      this.setData({
        history
      })
      items = this.data.allItems.filter((x) => x.position == "slot");
      // this.isOver = items.length > 6;
      this.setData({
        isOver:items.length > 6
      })
      items = this.data.allItems.filter((x) => x.position == "dispel");
      // this.isVictory = items.length == this.data.allItems.length;
      this.setData({
        isVictory:items.length == this.data.allItems.length
      })

      // console.log('slotAddItem done');
      // console.log(this);
    },
    //打乱
    disarange() {
      if (this.data.isOver) {
        return;
      }
      if (this.data.rangeNum == 0) {
        return;
      }
      let items = this.data.allItems.filter(
        (x) =>
          x.position == "assist-left" ||
          x.position == "assist-right" ||
          x.position == "hall"
      );
      console.log(this.data.history);
      this.data.history.push(
        items.map((x) => {
          return {
            id: x.id,
            // spirit: x.spirit,
            order: x.order,
            position: x.position,
            layer: x.layer,
            sno: x.sno,
          };
        })
      );
      items = items
        .map((x) => {
          return {
            id: x.id,
            spirit: x.spirit,
            order: Math.random(),
          };
        })
        .sort((a, b) => a.order - b.order);

      let left = this.data.assistLeft.length;
      let right = this.data.assistRight.length;
      let layer = Math.max(...this.data.hallItems.map((x) => x.layer)) || 0;
      items = this.resetPosition(items, left, right, layer + 1);
      let newItems = this.data.allItems.filter(
        (x) =>
          x.position != "assist-left" &&
          x.position != "assist-right" &&
          x.position != "hall"
      );
      // newItems = [];
      newItems.push(...items);
      this.setData({
        allItems:newItems,
        rangeNum:this.data.random--
      })
      // this.allItems = newItems;
      // this.rangeNum--;
    },
    //排序
    resetPosition(items, left, right, layer) {
      // console.log(items);
      let index = 0;
      for (let i = 0; i < left; i++) {
        items[index].layer = i;
        items[index++].position = "assist-left";
      }
      for (let i = 0; i < right; i++) {
        items[index].layer = i;
        items[index++].position = "assist-right";
      }
      for (; index < items.length; index++) {
        items[index].layer = Math.floor(Math.random() * layer);
        items[index].position = "hall";
      }
      for (let i = 0; i < layer || 0; i++) {
        let cols = i % 2 == 1 ? 7 : 6;
        let total = cols * cols;
        // eslint-disable-next-line no-constant-condition
        while (true) {
          let item = items.find(
            (x) => x.position == "hall" && x.layer == i && x.sno === undefined
          );
          if (!item) {
            break;
          }
          let sno = Math.floor(Math.random() * total);
          while (
            items.find(
              (x) => x.position == "hall" && x.layer == i && x.sno == sno
            )
          ) {
            sno = Math.floor(Math.random() * total);
          }
          item.sno = sno;
        }
      }
      return items;
    },
    //上去三个
    toUp3() {
      // 游戏结束
      if (this.data.isOver) {
        console.log('this.data.isOver');
        return;
      }
      // console.log(this.data.toupNum);
      if (this.data.toupNum == 0) {
        console.log('this.data.toupNum == 0');
        return;
      }
      if (this.properties.slotItems.length < 3) {
        console.log('this.properties.slotItems.length < 3');
        return;
      }
      let idx = this.properties.toupItems.length == 0 ? 0 : 3;
      console.log('idx',idx);
      let his = [];
      for (let i = 0; i < 3; i++) {
        console.log(this.properties.slotItems);
        let s = this.properties.slotItems[i];
        let item = this.data.allItems.find((x) => x.id == s.id);
        his.push({
          id: item.id,
          position: item.position,
          order: item.order,
        });
        item.position = "to-up";
        item.order = idx++;
        // console.log(item.order);
      }
      console.log(his);
      // this.setData({
      //   allItems:this.data.allItems

      // })
      // console.log(his);
      // this.data.history.push(his);
      let history = [his,...this.data.history]
      this.setData({
        history
      })//err
      // this.toupNum--;
      this.setData({
        toupNum:this.data.toupNum-1
      })
    },
    //撤销
    revoke() {
      if (this.data.isOver || this.data.isVictory) {
        return;
      }
      if (this.data.revokeNum == 0) {
        return;
      }
      if (this.data.history.length == 0) {
        return;
      }
      console.log(this.data.history);
      let his = this.data.history.pop();
      let len = his.length;
      for (let i = 0; i < len; i++) {
        let act = his.pop();
        let item = this.data.allItems.find((x) => x.id == act.id);
        item.position = act.position;
        if (act.order !== undefined) {
          item.order = act.order;
        }
        if (act.sno !== undefined) {
          item.sno = act.sno;
        }
        if (act.layer !== undefined) {
          item.layer = act.layer;
        }
      }
      // this.revokeNum--;
      this.setData({
        revokeNum:this.data.revokeNum-1
      })
    },
  }
})
